from django import template
import math

register = template.Library()

@register.filter
def columnize(lst, n):
    """
    >>> list(columnize(range(8), 3))
    [[0, 1, 2], [3, 4, 5], [6, 7]]
    """
    lst = list(lst)
    n = int(n)
    per_bit = int(math.ceil(float(len(lst)) / n))
    for i in range(n):
        yield lst[i * per_bit: (i + 1) * per_bit]

@register.tag
def assign_var(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, varname, value = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires exactly two arguments" % token.contents.split()[0])
    if not (varname[0] == varname[-1] and varname[0] in ('"', "'")):
        raise template.TemplateSyntaxError( "%r tag's argument should be in quotes" % tag_name)
    return AssignNode(varname[1:-1], value)

class AssignNode(template.Node):
    def __init__(self, varname, value):
        self.varname = varname
        self.value = template.Variable(value)

    def render(self, context):
        context[self.varname] = self.value.resolve(context)
        return ''
